using System;
using System.Collections.Generic;

using RexToy.Compiler.Lexical;

namespace RexToy.AOP
{
    public class LexicalParser : LexicalParser<TokenType, StatusMatrix>
    {
        public override void SetParseContent(string text)
        {
            _text = text.Trim();
            _index = 0;
            _status = ParserStatus.Start;
            _tokens = new List<Token<TokenType>>();
        }

        protected override Token<TokenType> CreateNewToken(int index)
        {
            return new Token(index);
        }

        public override List<Token<TokenType>> Parse()
        {
            curr = new Token(_index);
            char ch = GetNextChar();
            while (ch != (char)0)
            {
                _status = _matrix.GetStatusTransform(_status, ch);
                if (_status == ParserStatus.Error)
                    ExceptionHelper.ThrowWeaveSyntax(_text);

                if (!_matrix.TokenTerminated)
                    curr.Add(ch);

                ch = GetNextChar();
            }

            AcceptLastToken(null, new LexicalParseEventArgs(ch, _status));//Note:Last token.

            PostProcess();

            return _tokens;
        }

        private void PostProcess()
        {
            //Note:Combine ..
            List<Token<TokenType>> list = new List<Token<TokenType>>();
            for (int i = 0; i < _tokens.Count; i++)
            {
                if (i < _tokens.Count - 1)
                {
                    if (_tokens[i].TokenType == TokenType.DOT && _tokens[i + 1].TokenType == TokenType.DOT)
                    {
                        Token any = new Token(_tokens[i].Position);
                        any.TokenType = TokenType.ANY;
                        any.Add("..");
                        list.Add(any);
                        i++;
                    }
                    else
                    {
                        list.Add(_tokens[i]);
                    }
                }
                else
                    list.Add(_tokens[i]);
            }
            _tokens = list;
        }
    }
}
